package com.tomkk;

import com.google.gson.Gson;
import com.tomkk.entity.User;
import com.tomkk.utils.MysqlOperation;
import com.tomkk.utils.Error;
import com.tomkk.utils.Success;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

/**
 * Created by Tomkk on 2016/5/23.
 */
@WebServlet(name = "AllUsersServlet",urlPatterns = "/getAllUsers")
public class AllUsersServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        Gson gson = new Gson();
        String sql = "SELECT user_id,username,nickname,email,mobile,realname,role,headimage,user_isuse FROM user WHERE role!=3";
        MysqlOperation operation = new MysqlOperation();
        operation.checkConn();
        ResultSet resultSet = operation.query(sql);
        ArrayList users = new ArrayList<>();
        String json = null;
        if(resultSet == null){
            Error error = new Error(2,"服务器异常");
            json = gson.toJson(error);

        }
        else{
            try {
                while(resultSet.next()){
                    String nickname = resultSet.getString("nickname");
                    String email = resultSet.getString("email");
                    String mobile = resultSet.getString("mobile");
                    String realname = resultSet.getString("realname");
                    String headimage = resultSet.getString("headimage");
                    int role = resultSet.getInt("role");
                    String username = resultSet.getString("username");
                    int id = resultSet.getInt("user_id");
                    boolean isuse = resultSet.getBoolean("user_isuse");
                    User user = new User(id,username,nickname,email,mobile,realname,role,headimage,isuse);
                    users.add(user);
                }
                json = gson.toJson(new Success(0,users));
            } catch (SQLException e) {
                e.printStackTrace();
                PrintWriter writer = response.getWriter();
                json = gson.toJson(new Error(2,"服务器错误"));
                writer.print(json);
                writer.flush();
                return;
            }
        }
        PrintWriter writer = response.getWriter();
        writer.print(json);
        writer.flush();
        try {
            operation.closeDB();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
